package com.sxm.yiwei.activitis;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sxm.yiwei.R;
import com.sxm.yiwei.tools.BookPayActivity;
import com.sxm.yiwei.tools.ErrType;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.DecimalFormat;
import java.util.List;

public class FwBuyServiceActivity extends BaseActivity implements View.OnClickListener{

    private Button add;
    private Button reduce;
    private TextView result;
    private ImageView febuyback;
    private SharedPreferences sharedPreferences;
    private String token;
    private String userId;
    private String appId;
    private Button servicebt;
    private String id;
    private TextView price;
    private String price1;
    private EditText message;
    private LinearLayout getlink;
    private TextView linkname;
    private TextView linkaddress;
    private List backLink;
    private String linkId;
    private Handler h = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            DecimalFormat    df   = new DecimalFormat("######0.00");
            switch (msg.what){

                case 1: //加
                    Double aDouble ;
                    if (String.valueOf(price.getText()).equals("")){
                        aDouble=0.0;
                    }else {
                        aDouble= Double.valueOf(String.valueOf(price.getText()));
                    }

                    df.format(aDouble);
                    Double aDouble1 = Double.valueOf(price1);
                    double v1 = aDouble + aDouble1;
                    df.format(v1);
                    price.setText(String.valueOf(df.format(v1)));
                    break;
                case 2: // 减
                     String r = String.valueOf(price.getText());
                    Double rDouble=Double.valueOf(r);
                    df.format(rDouble);
                    if (rDouble>Double.valueOf(price1)){
                        double v2 = rDouble - Double.valueOf(price1);

                        price.setText(String.valueOf( df.format(v2)));
                    }else {
                        price.setText("0");
                    }
                    break;
            }
        }
    };
    private CheckBox buybox;
    private TextView buyx;
    private AlertDialog dialog;
    private ImageView backmain;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fw_buy_service);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", "");
        userId = sharedPreferences.getString("userId", "");
        appId = sharedPreferences.getString("appid", "");
        Intent intent = getIntent();
        id = intent.getStringExtra("id");
        price1 = intent.getStringExtra("price");
        initFWBuyView();
        buybox.setChecked(true);
        price.setText(price1);
        result.setText("1");
    }

    private void initFWBuyView() {
        backmain = (ImageView) findViewById(R.id.fwbuyservice_backmain);
        add = (Button) findViewById(R.id.add);
        reduce = (Button) findViewById(R.id.reduce);
        result = (TextView) findViewById(R.id.t_result);
        febuyback = (ImageView) findViewById(R.id.fw_buyserviceback);
        servicebt = (Button) findViewById(R.id.buy_servicebt);
        price = (TextView) findViewById(R.id.buyservice_price);
        message = (EditText) findViewById(R.id.buyservice_message);
        getlink = (LinearLayout) findViewById(R.id.buyservice_link);
        linkname = (TextView) findViewById(R.id.buyservice_linkname);
        linkaddress = (TextView) findViewById(R.id.buyservice_linkaddress);
        buybox = (CheckBox) findViewById(R.id.buy_servicebox);
        buyx = (TextView) findViewById(R.id.buy_x);
        backmain.setOnClickListener(this);
        buybox.setChecked(true);
        buyx.setOnClickListener(this);
        add.setOnClickListener(this);
        reduce.setOnClickListener(this);
        result.setOnClickListener(this);
        febuyback.setOnClickListener(this);
        servicebt.setOnClickListener(this);
        getlink.setOnClickListener(this);
       buybox.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.fw_buyserviceback:
                finish();
                break;
            case R.id.buy_x:
                Intent i = new Intent(FwBuyServiceActivity.this,WEBXActivity.class);
                i.putExtra("from","buy");
                i.putExtra("url", InternetAddressUtis.XBUYSERVICER);
                startActivity(i);
                break;
            case R.id.buy_servicebox:
                if (!buybox.isChecked()){
                    buybox.setChecked(false);
                }
                break;

            case R.id.buy_servicebt:
                if (!buybox.isChecked()){
                    Toast.makeText(this, "请阅读同意相关协议", Toast.LENGTH_SHORT).show();
                }else {
                    String text = String.valueOf(linkaddress.getText());
                    if (text.equals("")){
                        Toast.makeText(this, "请选择联系人", Toast.LENGTH_SHORT).show();
                    }else {
                        AlertDialog.Builder builder = new AlertDialog.Builder(FwBuyServiceActivity.this,R.style.NoBackGroundDialog);
                        View view = LayoutInflater.from(FwBuyServiceActivity.this).inflate(R.layout.progress_dialog, null);
                        ProgressBar diapro = (ProgressBar) view.findViewById(R.id.pro_dia);
                        builder.setView(view);
                        dialog = builder.create();
                        dialog.show();
                        buyService();
                    }
                }


                break;
            case R.id.buyservice_link:
               // Intent getcall = new Intent(FwBuyServiceActivity.this,AddCloseActivity.class);
                Intent getcall = new Intent(FwBuyServiceActivity.this,MineServicer.class);
                getcall.putExtra("from","buyservice");
                startActivityForResult(getcall,1003);
                break;
            case R.id.add:
                int aNumber = Integer.parseInt(String.valueOf(result.getText()));
                aNumber++;
                result.setText(String.valueOf(aNumber));

               h.sendEmptyMessage(1);


                break;
            case R.id.reduce:
                int rNumber = Integer.parseInt(String.valueOf(result.getText()));
                if (rNumber>0){
                    rNumber--;
                    result.setText(String.valueOf(rNumber));

                    h.sendEmptyMessage(2);
                }else{
                    Toast.makeText(this, "对不起,奴家不接受调戏", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
        // 购买服务
    private void buyService() {
        final String amount = (String) price.getText();
        String messageText = String.valueOf(message.getText());
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.BUYSERVICE);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        final JSONObject object = new JSONObject();
        object.put("serviceId",id);
        object.put("contactId",linkId);
        object.put("count", result.getText());
        object.put("totalAmount",amount);
            if (messageText!=null&messageText!=""){
                object.put("message",messageText);
            }else {}

        params.setBodyContent(object.toJSONString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                dialog.dismiss();
                JSONObject object1 = JSON.parseObject(result);
                String status = object1.getString("status");
                String data = object1.getString("data");
                JSONObject object2 = JSON.parseObject(data);
                String orderId = object2.getString("orderId");
                if (status.equals("1")){
                    Intent intent = new Intent(FwBuyServiceActivity.this,BookPayActivity.class);
                    intent.putExtra("id",orderId);
                    intent.putExtra("amount",amount);
                    intent.putExtra("from","buyservice");
                    intent.putExtra("alipay",InternetAddressUtis.PAYALIBUYSERVICE);
                    intent.putExtra("yivipay",InternetAddressUtis.PAYBUYSERVICE);
                    startActivity(intent);
                }
               // finish();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ErrType.errType(FwBuyServiceActivity.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1003){
            if (data==null){

            }else {
                Bundle extras = data.getExtras();
                linkId = (String) extras.get("id");
                String name1 = String.valueOf(extras.get("name1"));
                String address1 = String.valueOf(extras.get("address1"));
                String phone1 = String.valueOf(extras.get("phone1"));
                linkname.setText(name1+" "+phone1);
                linkaddress.setText(address1);
            }


        }
    }
}
